package com.tang.state;

import com.tang.bean.WaterSensor;
import com.tang.functions.WaterSensorMapFunction;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.scala.typeutils.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Map;

/**
 * 统计每种传感器每种水位值出现的次数。
 *
 * @author tang
 * @since 2023/7/11 11:00
 */
public class KeyedMapStateDemo {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());

        env.socketTextStream("192.168.70.141", 7777)
                .map(new WaterSensorMapFunction())
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((element, recordTimestamp) -> element.getTs() * 1000L)
                ).keyBy(WaterSensor::getId)
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {

                    // 1. 定义MapState
                    private MapState<Integer, Integer> mapState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        super.open(parameters);
                        // 2. 在Open方法中初始化状态
                        mapState = getRuntimeContext().getMapState(new MapStateDescriptor<>("mapState", Types.INT(), Types.INT()));
                    }

                    @Override
                    public void processElement(WaterSensor waterSensor,
                                               KeyedProcessFunction<String, WaterSensor, String>.Context ctx,
                                               Collector<String> out) throws Exception {
                        // 1.判断是否存在vc对应的key
                        Integer vc = waterSensor.getVc();
                        if (mapState.contains(vc)) {
                            // 1.1 如果包含这个vc的key，直接对value+1
                            Integer count = mapState.get(vc);
                            mapState.put(vc, ++count);
                        } else {
                            // 1.2 如果不包含这个vc的key，初始化put进去
                            mapState.put(vc, 1);
                        }
                        // 2.遍历Map状态，输出每个k-v的值
                        StringBuilder outStr = new StringBuilder();
                        outStr.append("\n======================================\n");
                        outStr.append("传感器id为").append(waterSensor.getId()).append("\n");
                        for (Map.Entry<Integer, Integer> vcCount : mapState.entries()) {
                            outStr.append(vcCount.toString()).append("\n");
                        }
                        outStr.append("======================================\n");

                        out.collect(outStr.toString());

//                                mapState.get();          // 对本组的Map状态，根据key，获取value
//                                mapState.contains();     // 对本组的Map状态，判断key是否存在
//                                mapState.put(, );        // 对本组的Map状态，添加一个 键值对
//                                mapState.putAll();       // 对本组的Map状态，添加多个 键值对
//                                mapState.entries();      // 对本组的Map状态，获取所有键值对
//                                mapState.keys();         // 对本组的Map状态，获取所有键
//                                mapState.values();       // 对本组的Map状态，获取所有值
//                                mapState.remove();       // 对本组的Map状态，根据指定key，移除键值对
//                                mapState.isEmpty();      // 对本组的Map状态，判断是否为空
//                                mapState.iterator();     // 对本组的Map状态，获取迭代器
//                                mapState.clear();        // 对本组的Map状态，清空

                    }

                }).print();

        env.execute();
    }

}
